﻿/********************************************************************
	文件:	MeshDisplay.cs
	作者:	Pangdudu
	日期:	2021/03/02
	描述:	显示Mesh上法线和切线的脚本
*********************************************************************/

using UnityEngine;

[RequireComponent(typeof(MeshFilter))]
public class MeshDisplay : MonoBehaviour
{
    public bool showNormals = true;
    public bool showTangents;
    public float displayLengthScale = 1.0f;

    public Color normalColor = Color.red;
    public Color tangentColor = Color.blue;

    private void OnDrawGizmosSelected()
    {
        var meshFilter = GetComponent<MeshFilter>();
        if (meshFilter == null)
        {
            Debug.LogWarning("Cannot find MeshFilter");
            return;
        }
        var mesh = meshFilter.sharedMesh;
        if (mesh == null)
        {
            Debug.LogWarning("Cannot find mesh");
            return;
        }
        var doShowNormals = showNormals && mesh.normals.Length == mesh.vertices.Length;
        var doShowTangents = showTangents && mesh.tangents.Length == mesh.vertices.Length;

        foreach (var idx in mesh.triangles)
        {
            var vertex = transform.TransformPoint(mesh.vertices[idx]);

            if (doShowNormals)
            {
                var normal = transform.TransformDirection(mesh.normals[idx]);
                Gizmos.color = normalColor;
                Gizmos.DrawLine(vertex, vertex + normal * displayLengthScale);
            }
            if (doShowTangents)
            {
                var tangent = transform.TransformDirection(mesh.tangents[idx]);
                Gizmos.color = tangentColor;
                Gizmos.DrawLine(vertex, vertex + tangent * displayLengthScale);
            }
        }
    }
}